#include "addfriendsender.h"
#include "ui_addfriendsender.h"
#include "user.h"
//#include "maininterfacewidget.h"
#include <QHostAddress>
#include <QMessageBox>
addfriendsender::addfriendsender(QWidget *parent,user userSelf,QString num,int type) :
    QDialog(parent),
    ui(new Ui::addfriendsender)
{
    ui->setupUi(this);
    this->userSelf = userSelf;
    //QString tmp=type;
    if(type>0)
        ui->receiverId->setText(num);
}
void addfriendsender::on_btn_send_addfriendsender_clicked()
{
    //Sender创建
    UserBrief Sender;
    Sender = {
        userSelf.getUserId(),//id
        userSelf.getUserName(),//username
        "",//photo
        userSelf.getUserGender()//gender
    };
    //get content
    QString Brief = ui->messageSendTextEdit->text();//传输服务器
    QString senderToken = userSelf.getUserPassword();
    QString receiverId = ui->receiverId->text();
    receiverId.toLongLong();//id转化为long long
    //sender信息
    QJsonObject senderValue{//发送给后端的添加人
        {"id", Sender.id.toInt()},
        {"username", Sender.username},
        {"photo", ""},
        {"gender", Sender.gender.toInt()}
    };
    qDebug()<<"SenderValue"<<senderValue;


    QString resourcePath = ":/asset/config/config.json";
    QFile jsonFile(resourcePath);
    if (jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
    QByteArray jsonData = jsonFile.readAll();
    // 将 JSON 数据转换为 QVariant 对象
    QJsonParseError error;
    QJsonObject result = QJsonDocument::fromJson(jsonData, &error).object();
    QJsonObject jsonUrl = QJsonDocument::fromJson(jsonData).object();
    qDebug() << "url :" << jsonUrl;
    jsonFile.close();
    QVariantMap urlVariantMap = jsonUrl.toVariantMap();
    QMap urlMap = urlVariantMap.value("server").toMap();
    host = urlMap.value("host").toString();
    port = urlMap.value("port").toString();
    }
    QNetworkRequest request(QUrl("http://"+host+':'+port+"/slimarveous/add_friend"));
    //QNetworkRequest request(QUrl("http://localhost:19999/slimarveous/add_friend"));



    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json2");
    //QJsonObject json2;
    QJsonObject json2{
        {"token",senderToken},
        {"sender",senderValue},
        {"receiver_id",receiverId.toInt()},
        {"brief", Brief}
    };
    QJsonDocument doc(json2);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    QNetworkReply *reply = manager.post(request, data);
    //qDebug()<<"data"<<data;
    connect(reply, &QNetworkReply::finished, [=](){});
    this->close();
    QMessageBox:: information(this, "好友请求","你好，"+userSelf.getUserName()+"! "+"你已向用户id为：" +receiverId+"的好友发送请求！");
    //跳转到主界面
}


void addfriendsender::on_btn_clear_addfriendsender_clicked()
{
    ui->messageSendTextEdit->clear();
    ui->receiverId->clear();
}


addfriendsender::~addfriendsender()
{
    delete ui;
}
